package org.example.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JSONUtils {

    // 创建对象映射工具类
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * 将对象转换成JSON
     * @param object
     * @return
     * @throws JsonProcessingException
     */
    public static String toJSON(Object object) throws JsonProcessingException {
        // 把对象以字符串的形式写出去，就变成了json
        return OBJECT_MAPPER.writeValueAsString(object);
    }

    /**
     * 将JSON转换成对象
     * @param json
     * @param clazz
     * @return
     * @param <T>
     * @throws JsonProcessingException
     */
    public static <T> T toBean(String json, Class<T> clazz) throws JsonProcessingException {
        return OBJECT_MAPPER.readValue(json, clazz);
    }
}
